package day_2023_7_to_10;

/**
 * @author haomin
 * @date 2023/08/06 23:36
 **/

public class Day_8_6 {
    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }

    class Solution {
        Node head, pre;
        public Node treeToDoublyList(Node root) {
            if(root == null) return null;
            treeToDoublyListHelper(root);
            head.left = pre;
            pre.right = head;
            return head;
        }
        public void treeToDoublyListHelper(Node root) {
            if(root == null) return;
            treeToDoublyListHelper(root.left);
            if(head == null) head = root;
            else {
                pre.right = root;
                root.left = pre;
            }
            pre = root;
            treeToDoublyListHelper(root.right);
        }
    }
}